package com.stiff.manage.controller;

import com.github.pagehelper.PageInfo;
import com.stiff.common.bean.EasyUIResult;
import com.stiff.manage.pojo.Item;
import com.stiff.manage.service.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("item")
public class ItemController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ItemController.class);
    @Autowired
    private ItemService itemService;
    /**
     * 新增商品
     * @param item
     * @param desc
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Void> save(Item item, @RequestParam("desc")String desc,@RequestParam("itemParams")String itemParams){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【新增商品】item={}，desc={}",item,desc);
            }
            if(StringUtils.isEmpty(item.getTitle())){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            this.itemService.saveItem(item,desc,itemParams);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【新增商品】itemId={}",item.getId());
            }
            return ResponseEntity.status(HttpStatus.CREATED).build();
        } catch (Exception e) {
            LOGGER.error("【新增商品失败！】title="+item.getTitle()+",cid="+item.getCid(),e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 删除商品
     * @param ids
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<Void> deleteItems(@RequestParam(value = "ids")String ids){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【删除商品】ids={}", ids);
            }
            List<Object> idList = this.getIdsList(ids);
            if(idList.isEmpty()){
                return ResponseEntity.<Void>badRequest().build();
            }
            this.itemService.deleteItemByIds(idList);
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            LOGGER.error("【删除商品失败！】ids=["+ids+"]",e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    /**
     * 查询商品列表
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<EasyUIResult> queryItemList(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                                      @RequestParam(value = "rows",defaultValue = "30")Integer rows){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【查询商品列表】page={}，rows={}",page,rows);
            }
            PageInfo<Item> itemPageInfo = this.itemService.queryPageList(page, rows);
            EasyUIResult easyUIResult = new EasyUIResult(itemPageInfo.getTotal(),itemPageInfo.getList());
            return ResponseEntity.ok(easyUIResult);
        } catch (Exception e) {
            LOGGER.error("【查询商品失败！】page="+page+",rows="+rows,e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    /**
     * 根据商品ID查询Item
     * @param itemId
     * @return
     */
    @RequestMapping(value = "{itemId}",method = RequestMethod.GET)
    public ResponseEntity<Item> queryItemList(@PathVariable("itemId")Long itemId){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【查询商品】itemId={}",itemId);
            }
            Item item = this.itemService.queryById(itemId);
            if(null==item){
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
            return ResponseEntity.ok(item);
        } catch (Exception e) {
            LOGGER.error("【查询商品失败！】itemId="+itemId,e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    /**
     * 修改商品
     * @param item
     * @param desc
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<Void> update(Item item, @RequestParam("desc")String desc,@RequestParam("itemParams")String itemParams){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【修改商品】item={}，desc={}",item,desc);
            }
            if(StringUtils.isEmpty(item.getTitle())){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            this.itemService.updateItem(item,desc,itemParams);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【修改商品】itemId={}",item.getId());
            }
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            LOGGER.error("【修改商品失败！】title="+item.getTitle()+",cid="+item.getCid(),e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    @RequestMapping(value = "status",method = RequestMethod.PUT)
    public ResponseEntity<Void> switchItemsStatus(@RequestParam(value = "ids")String ids,
                                                  @RequestParam(value = "itemStatus",defaultValue = "1")int itemStatus){
        try {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【修改商品状态】Ids=[{}]，ItemStatus={}",ids,itemStatus);
            }
            List<Object> idList = this.getIdsList(ids);
            if(!(1 == itemStatus || 2 == itemStatus || 3 == itemStatus)){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            this.itemService.updateItemsStatus(idList,itemStatus);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("【修改商品状态】Ids={}",ids);
            }
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            LOGGER.error("【修改商品状态失败！】Ids=["+ids+"],ItemStatus="+itemStatus,e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    private List<Object> getIdsList(String ids){
        List<String> list = Arrays.asList(ids.split(","));
        if (!list.isEmpty()) {
            List<Object> idList = new ArrayList<>();
            for(String str : list) {
                Long i = Long.parseLong(str);
                idList.add(i);
            }
            return idList;
        }
        return null;
    }
}
